<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | CMS缓存
// +----------------------------------------------------------------------
namespace app\cms\helper;

use Inphp\Core\Config;
use Inphp\Core\Modules;
use Inphp\Core\Service;

class cache
{
    /**
     * 设置缓存
     * @param array $params
     * @param array $data
     * @param string $group
     */
    public static function set(array $params, array $data, string $group)
    {
        $config = Modules::getModule("cms")->getConfig();
        $cache = $config["cache"] ?? false;
        if (!$cache) {
            return;
        }
        ksort($params);
        $key = md5(json_encode($params));
        //存放目录
        $dir = Config::get("define.cache")."/cms".(!empty($group) ? "/{$group}" : "");
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }
        $file = $dir."/{$key}.json";
        $content = [
            "time"      => time(),
            "data"      => $data
        ];
        @file_put_contents($file, json_encode($content, 256));
    }

    /**
     * 获取缓存
     * @param array $params
     * @param string $group
     * @return array|null
     */
    public static function get(array $params, string $group): ?array
    {
        $config = Modules::getModule("cms")->getConfig();
        $cache = $config["cache"] ?? false;
        if (!$cache) {
            return null;
        }
        $cacheTime = $config["cacheTime"] ?? 86400;
        $cacheTime = is_numeric($cacheTime) && $cacheTime >= 3600 ? ceil($cacheTime) : 86400;
        ksort($params);
        $key = md5(json_encode($params));
        //存放目录
        $dir = Config::get("define.cache")."/cms".(!empty($group) ? "/{$group}" : "");
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }
        $file = $dir."/{$key}.json";
        if (!is_file($file)) {
            return null;
        }
        $content = @file_get_contents($file) ?? [];
        if (empty($content)) {
            return null;
        }
        $json = @json_decode($content, true) ?? [];
        if (empty($json)) {
            return null;
        }
        //取缓存时间
        $time = $json["time"] ?? 0;
        $time = is_numeric($time) && $time > 0 ? ceil($time) : 0;
        if ($time >= time() - $cacheTime) {
            return $json["data"] ?? [];
        }
        return [];
    }

    /**
     * 清除指定目录的缓存
     * @param string|null $group
     */
    public static function clean(?string $group = null)
    {
        if (Service::isCLI()) {
            $dir = Config::get("define.cache")."/cms".(!empty($group) ? "/{$group}" : "");
            //直接删除
            self::removeDir($dir);
        } else {
            //以命令方式支行，以免文件过多，删除缓慢
            CMD_RUN("app.cms.cmd.cleanCache", [
                "group"     => $group ?? ''
            ], true);
        }
    }

    /**
     * 删除文件夹
     * @param string $dir
     * @return bool
     */
    public static function removeDir(string $dir): bool
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if($file != "." && $file != "..") {
                $path = $dir."/".$file;
                if(!is_dir($path)) {
                    unlink($path);
                } else {
                    self::removeDir($path);
                }
            }
        }
        @closedir($dh);
        if(rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}